// utils/mapUtils.js
// 此百度接口不太好使,已经没用了,改用腾讯地图了
const BAIDU_AK = 'Ko74DyAXyiVRh7oUBzfxO0x3GLchKfRC'; // 你的百度地图AK:在百度控制台申请

function getCoordinates(location) {
  if (!location || typeof location !== 'string') {
    return Promise.reject(new Error('无效的地址参数'))
  }
  const encodedAddress = encodeURIComponent(location)
  return new Promise((resolve, reject) => {
    wx.request({
      url: 'https://api.map.baidu.com/geocoding/v3/',
      method:'GET',
      data:{
        address: encodedAddress,
        output: 'json',
        ak: BAIDU_AK
      },
      success: (res) => {
        console.log('res:',res)
        if (res.statusCode === 200 && res.data.status === 0) {
          resolve({
            latitude: res.data.result.location.lat,
            longitude: res.data.result.location.lng
          })
        } else {
          reject(new Error(`地理编码失败: ${res.data.message}`))
        }
      },
      fail: (err) => {
        reject(new Error(`网络请求失败: ${err.errMsg}`))
      }
    })
  })
}

// 导出模块
module.exports = {
  getCoordinates
}
